import datetime
from PySide6.QtWidgets import QDialog,QMessageBox
from sqlalchemy.orm import Session
from PySide6.QtCore import QDate

from views.salary.position.position.operationposition import Ui_operationpostionDialog
from views.person.model.person import PersonBaseInfo
from views.salary.model.salary import Position
from settings.publicvar import engine


class OperationPositionView(QDialog,Ui_operationpostionDialog):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_state(is_state)
        self.setFormStructure(data)

        self.addbtn.clicked.connect(self.addPositionFun)
        self.changbtn.clicked.connect(self.changePositionFun)
        self.deletebtn.clicked.connect(self.deletePositionFun)
        self.retsetbtn.clicked.connect(self.resetPositionFun)
        self.name.editingFinished.connect(self.nameFinishedFun)

    # 状态
    def if_state(self,is_state):
        if is_state == 'add':
            self.titlelabel.setText('添加岗位信息')
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('检验身份信息是否有效')
            self.changbtn.hide()
            self.deletebtn.hide()
        elif is_state == 'view':
            self.titlelabel.setText('查看岗位信息')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.changbtn.hide()
            self.retsetbtn.hide()
            self.deletebtn.hide()
        elif is_state == 'change':
            self.titlelabel.setText('修改岗位信息')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.deletebtn.hide()
        else:
            self.titlelabel.setText('删除岗位信息')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.changbtn.hide()
            self.retsetbtn.hide()

    # 表单结构
    def setFormStructure(self, data):
        if data:
            self.idx.setText(str(data[0]))
            self.name.setText(data[1])
            self.acquisition_method.setCurrentText(data[2])
            self.post_grade.setCurrentText(data[3])
            date = QDate.fromString(data[4], "yyyy-MM-dd")
            if date.isValid():
                self.acquisition_date.setDate(date)
            else:
                self.acquisition_date.setDate(QDate(1, 1, 1))
                self.acquisition_date.setSpecialValueText("请选择日期")
            date = QDate.fromString(data[5], "yyyy-MM-dd")
            if date.isValid():
                self.hire_date.setDate(date)
            else:
                self.hire_date.setDate(QDate(1, 1, 1))
                self.hire_date.setSpecialValueText("请选择日期")
            date = QDate.fromString(data[6], "yyyy-MM-dd")
            if date.isValid():
                self.execute_date.setDate(date)
            else:
                self.execute_date.setDate(QDate(1, 1, 1))
                self.execute_date.setSpecialValueText("请选择日期")
            self.post_type.setCurrentText(data[7])
            self.mark.setText(data[8])

    # 获取表单数据
    def get_form_data(self):
        idx = self.idx.text()
        acquisition_method = self.acquisition_method.currentText()
        post_grade = self.post_grade.currentText()
        date = self.acquisition_date.date()
        acquisition_date = datetime.date(date.year(),date.month(),date.day())
        date = self.hire_date.date()
        hire_date = datetime.date(date.year(), date.month(), date.day())
        date = self.execute_date.date()
        execute_date = datetime.date(date.year(), date.month(), date.day())
        post_type = self.post_type.currentText()
        mark = self.mark.text()
        data = {'acquisition_method':acquisition_method,'post_grade':post_grade,'acquisition_date':acquisition_date,
                           'hire_date':hire_date,'execute_date':execute_date,'post_type':post_type,'mark':mark}
        if idx == '':
            data = (False,data)
        else:
            data = (idx,data)
        return data

    # 添加数据
    def addPositionFun(self):
        data = self.get_form_data()
        if ~data[0]:
            data[1]['name_id'] = self.name_id
            with Session(engine) as session,session.begin():
                position = Position(**data[1])
                session.add(position)
                self.close()
                QMessageBox.information(None,'成功','添加成功')

    # 修改数据
    def changePositionFun(self):
        data = self.get_form_data()
        if data[0] == 0 or data[0]:
            with Session(engine) as session,session.begin():
                session.query(Position).filter(Position.id == data[0]).update(data[1])
                self.close()
                QMessageBox.information(None,'成功','数据修改成功！')


    # 删除数据
    def deletePositionFun(self):
        data = self.get_form_data()
        if data[0] == 0 or data[0]:
            with Session(engine) as session, session.begin():
                session.query(Position).filter(Position.id == data[0]).delete()
                self.close()
                QMessageBox.information(None, '成功', '数据删除%s成功！'%self.name.text().strip())

    # 重置数据
    def resetPositionFun(self):
        self.acquisition_method.setCurrentText('选择岗位等级')
        self.post_grade.setCurrentText('')
        self.acquisition_date.setDate(QDate(1,1,1))
        self.acquisition_date.setSpecialValueText("请选择日期")
        self.hire_date.setDate(QDate(1, 1, 1))
        self.hire_date.setSpecialValueText("请选择日期")
        self.execute_date.setDate(QDate(1, 1, 1))
        self.execute_date.setSpecialValueText("请选择日期")
        self.post_type.setCurrentText('')
        self.mark.setText('')

    # 姓名检验
    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session, session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                self.name.setText(personbase.name)
                self.name_id = personbase.id
            except:
                QMessageBox.critical(None, '失败', '没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')